package org.soenea.doitall.domain.command;

import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.command.CommandError;
import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.command.DomainCommand;
import org.dsrg.soenea.domain.helper.Helper;
import org.dsrg.soenea.service.SingleAppUniqueIdFactory;
import org.soenea.doitall.domain.model.group.Group;
import org.soenea.doitall.domain.model.group.GroupProxy;
import org.soenea.doitall.domain.model.group.mapper.GroupInputMapper;
import org.soenea.doitall.domain.model.group.mapper.GroupOutputMapper;
import org.soenea.doitall.domain.model.invite.Invite;
import org.soenea.doitall.domain.model.invite.InviteStatus;
import org.soenea.doitall.domain.model.invite.data.InviteTDG;
import org.soenea.doitall.domain.model.invite.mapper.InviteOutputMapper;
import org.soenea.doitall.domain.model.person.PersonProxy;
import org.soenea.doitall.domain.model.person.mapper.PersonInputMapper;

public class InviteUserCommand extends DomainCommand {

	public InviteUserCommand(Helper helper) {
		super(helper);
	}

	@Override
	public void setUp() throws CommandException {
	}

	@Override
	public void process() throws CommandException {
		try {
			long groupId = (Long) helper.getAttribute("id");
			long invitedID = (Long) helper.getAttribute("invitedID");
			long inviterID = (Long) helper.getSessionAttribute("userID");
			PersonProxy invited = new PersonProxy(invitedID);
			PersonProxy inviter = new PersonProxy(inviterID);
			Group group = GroupInputMapper.find(groupId);
			long id = 0L;
			try{
				id = SingleAppUniqueIdFactory.getMaxId(InviteTDG.BASE_NAME, InviteTDG.INVITE_ID);
			}catch( Exception e){
				//supress exception
			}
			Invite invite = new Invite( id, 0L, inviter,invited, group, InviteStatus.INVITED);
			group.getMembers().add(invite);
			InviteOutputMapper.insert(invite);
			helper.setRequestAttribute("group", group);
			helper.setRequestAttribute("people", PersonInputMapper.findAllWithoutGroup(groupId));
		} catch (MapperException e) {
			throw new CommandException(e);
		}
	}

	@Override
	public void tearDown() throws CommandError {
	}

}
